package com.baihan.angus.app.game.busshow.ui.user.album;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baihan.angus.app.game.basic.base.BaseActivity;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.busshow.BR;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.adps.AlbumAdp;
import com.baihan.angus.app.game.busshow.adps.PhotoListAdp;
import com.baihan.angus.app.game.busshow.databinding.ActivityAlbumBinding;
import com.baihan.angus.app.game.busshow.pop_dialog.SelectPicDialog;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.baihan.angus.app.game.common.bean.response.AlbumResponse;
import com.baihan.angus.app.game.common.bean.response.PicBean;
import com.baihan.angus.app.game.common.bean.response.UploadMultipleResponse;
import com.baihan.angus.app.game.common.util.imagepickerhelper.ImageOperateHelper;
import com.baihan.angus.app.game.common.util.media.IMediaInfo;
import com.baihan.angus.app.game.common.util.media.MediaGalleryActivity;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lcw.library.imagepicker.ImagePicker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.baihan.angus.app.game.busshow.adps.AlbumAdp.MAX_COUNT;

/**
 * 相册集
 */
@Route(path = ArouterAppPath.ALBUM_ACTIVITY)
public class AlbumActivity extends BaseActivity<ActivityAlbumBinding, AlbumVM> {

    private static final int OPEN_CAMERA = 0xb14;

    private AlbumAdp mAlbumAdp;
    private PhotoListAdp mPhotoListAdp;

    private SelectPicDialog mSelectPicDialog;

    private Map<String, Object> mCreateRequest = new HashMap<>();
    private List<PicBean> picsLists = new ArrayList<>();

    @Override
    protected int getContentLayout() {
        return R.layout.activity_album;
    }

    @Override
    protected int getViewModelId() {
        return BR.albumVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mVDBinding.titleView.setLeftOnClickListener(view -> finish());

        mVDBinding.titleView.setRightOnClickListener(view -> {
            if (null != mAlbumAdp.getSelectedMedias() && mAlbumAdp.getSelectedMedias().size() > 0) {
                mViewModel.transferFile(mAlbumAdp.getSelectedMedias());
            } else {
                Tooast.normalInfo("请添加照片");
            }
        });

        mAlbumAdp = new AlbumAdp(new AlbumAdp.OnTieziMediaAdpCallback() {
            @Override
            public void onAdd() {
                addMediaFile();
            }

            @Override
            public void preview(int index) {
                List<IMediaInfo> iMediaInfos = new ArrayList<>();
                for (String s : mAlbumAdp.getSelectedMedias()) {
                    iMediaInfos.add((IMediaInfo) () -> s);
                }
                MediaGalleryActivity.start(AlbumActivity.this, iMediaInfos, index, 1);
            }
        }, this);

        mVDBinding.rvPhotos.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        mVDBinding.rvPhotos.setAdapter(mAlbumAdp);

        mPhotoListAdp = new PhotoListAdp();
        mVDBinding.rvPhotoList.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        mPhotoListAdp.bindToRecycleView(mVDBinding.rvPhotoList);

        mPhotoListAdp.setOnItemClickListener(new PhotoListAdp.OnItemClickListener() {
            @Override
            public void preview(int index, List<IMediaInfo> list) {
                MediaGalleryActivity.start(AlbumActivity.this, list, index, 1);
            }
        });
    }

    @Override
    protected void initData() {
        mViewModel.getPhotoList();
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldAlbum.observe(this, new Observer<AlbumResponse.Data>() {
            @Override
            public void onChanged(AlbumResponse.Data data) {
                if (null != data.getPics() && data.getPics().size() > 0) {

                    //拼接picLists
                    picsLists.addAll(data.getPics());

                    mPhotoListAdp.setPicList(data.getPics());

                    mVDBinding.rvPhotoList.setVisibility(View.VISIBLE);
                    if (data.getPics().size() < 10) {
                        MAX_COUNT = 10 - data.getPics().size();
                        mVDBinding.rvPhotos.setVisibility(View.VISIBLE);
                    } else {
                        mVDBinding.rvPhotos.setVisibility(View.GONE);
                    }
                    mPhotoListAdp.addAll(data.getPics());
                } else {
                    mVDBinding.rvPhotos.setVisibility(View.VISIBLE);
                    mVDBinding.rvPhotoList.setVisibility(View.GONE);
                }
            }
        });

        mViewModel.mldMultiple.observe(this, new Observer<UploadMultipleResponse>() {
            @Override
            public void onChanged(UploadMultipleResponse uploadMultipleResponse) {
                if (null != uploadMultipleResponse.getData() && uploadMultipleResponse.getData().size() > 0) {
                    picsLists.addAll(uploadMultipleResponse.getData());
                    //拼接picLists
                    mCreateRequest.put("pics", picsLists);
                    mViewModel.createPhotoList(mCreateRequest);
                }
            }
        });
    }

    private void addMediaFile() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(List<String> permissionsGranted) {
                showDialog();
            }

            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                ToastUtils.showShort(R.string.open_permission);
            }
        }).request();
    }

    private void showDialog() {
        if (null == mSelectPicDialog) {
            mSelectPicDialog = new SelectPicDialog(this, new SelectPicDialog.Callback() {
                @Override
                public void onTakePhoto() {
                    ARouter.getInstance().build(ArouterAppPath.CAMERA_ACTIVITY).navigation(AlbumActivity.this, OPEN_CAMERA);
//                    PhotoUtil.openCameraImage(AlbumActivity.this);
                    mSelectPicDialog.dismiss();
                }

                @Override
                public void onAlbum() {
                    if (mAlbumAdp.getMediaSize() < MAX_COUNT) {
                        ImageOperateHelper.startImagePicker(AlbumActivity.this, null, MAX_COUNT - mAlbumAdp.getSelectedMedias().size(), true);
                    } else {
                        Tooast.normalInfo("最多选择10个");
                    }
                    mSelectPicDialog.dismiss();
                }
            });
        }
        mSelectPicDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageOperateHelper.REQUEST_SELECT_IMAGES_CODE) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                mAlbumAdp.addAll(imagePaths);
            }
        } else if (requestCode == OPEN_CAMERA) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> imagePaths = new ArrayList<>();
                String path = data.getStringExtra("path");
                if (!TextUtils.isEmpty(path)) {
                    imagePaths.add(path);
                    mAlbumAdp.addAll(imagePaths);
                }
            }
        }
//        else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
//            if (resultCode == RESULT_OK) {
//                File imageFile;
//                imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
//                Luban.with(this).load(imageFile)
//                        .setTargetDir(AppUtil.getLubanPath())
//                        .ignoreBy(100)
//                        .setCompressListener(new OnCompressListener() {
//                            @Override
//                            public void onStart() {
//                                showLoading("Compress");
//                            }
//
//                            @Override
//                            public void onSuccess(File file) {
//                                hideLoading("Compress");
//                                mViewModel.uploadFile(file);
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                hideLoading("Compress");
//                                Tooast.normalInfo(getString(R.string.compassPicFail));
//
//                            }
//                        }).launch();
//            }
//        }
    }
}